package com.fromfuture.xuhuidoc.cordova.plugin;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * Created by hp on 2017/6/27.
 */

public class PermissionPlugin extends CordovaPlugin {

    private Context permissionContext;
    private CallbackContext permissionCallbackContext;

    final int MYRECRDD = 1;

    private String PERMISSION_WRITE_EXTERNAL_STORAGE = "permission_write_external_storage";
    private String PERMISSION_CAMERA = "permission_camera";

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

        try {
            if (action.equals(PERMISSION_WRITE_EXTERNAL_STORAGE)) {
                permissionCallbackContext = callbackContext;
                storagepermission();
            } else if (action.equals(PERMISSION_CAMERA)) {
                permissionCallbackContext = callbackContext;
                camerapermission();
            }

        } catch (Exception e) {
            return false;
        }

        return false;
    }

    //6.0动态获取权限
    private void storagepermission() {
        if (ContextCompat.checkSelfPermission(cordova.getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                PackageManager.PERMISSION_GRANTED) {
        } else {
            //需要申请权限
            Toast.makeText(cordova.getActivity(), "请打开存储权限", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(cordova.getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

        }
    }

    private void camerapermission() {
        if (ContextCompat.checkSelfPermission(cordova.getActivity(), Manifest.permission.CAMERA) ==
                PackageManager.PERMISSION_GRANTED) {
        } else {
            //需要申请权限
            Toast.makeText(cordova.getActivity(), "请打开相机权限", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(cordova.getActivity(), new String[]{Manifest.permission.CAMERA}, 1);
        }


    }
}
